package com.fuze.navi.aspect;

import com.fuze.navi.common.Advice;
import com.fuze.navi.common.Constant;
import com.fuze.navi.common.NaviException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sepc_
 * @date 5/25/2021 15:14
 */
@Component
@Slf4j
@Aspect
@RequiredArgsConstructor
public class AuthAdminAspect {

    final StringRedisTemplate stringRedisTemplate;

    final HttpServletRequest request;

    private final static Integer DATA_LENGTH = 3;

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.fuze.navi.aspect.anno.AuthAdmin)")
    public void authPointCut() {
    }

    /**
     * 处理请求之前执行：校验token的角色
     */
    @Before(value = "authPointCut()")
    public void doBefore(JoinPoint point) {
        String token = request.getHeader(Constant.AUTH_TOKEN);
        String data = stringRedisTemplate.opsForValue().get(token);
        if (data == null) {
            throw new NaviException(Advice.TOKEN_EXPIRED);
        }
        String[] authData = data.split(Constant.DELIMITER);
        if (!DATA_LENGTH.equals(authData.length)) {
            throw new NaviException(Advice.TOKEN_VERIFICATION_FAILED);
        }
        String authority = authData[2];
        if (authority.equals(Constant.ROLE_USER.toString())) {
            throw new NaviException(Advice.FAILED_VERIFICATION_PERMISSION);
        }
    }


}

